/****************************************************
	文件：MotionBlurV2.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2020/8/17 17:23:55
	功能：运动模糊 V2
*****************************************************/

using System;
using UnityEngine;

namespace RenderingPractice
{
    public class MotionBlurV2 : PostEffectsBase
    {
        [Range(0.0f, 1.0f), Tooltip("模糊图像大小")]
        public float BlurSize = 0.5f;
        public Shader MotionBlurShaderV2;
        private Material mMotionBlurMat;

        private Camera mCamera;
        public Camera Camera
        {
            get
            {
                if (mCamera == null)
                {
                    mCamera = GetComponent<Camera>();
                }
                return mCamera;
            }
        }

        private Matrix4x4 mPreViewProjMatrix;

        public Material MotionBlurMat
        {
            get
            {
                mMotionBlurMat = CheckShaderAndCreateMaterial(MotionBlurShaderV2, mMotionBlurMat);
                return mMotionBlurMat;
            }
        }

        private void OnEnable()
        {
            Camera.depthTextureMode |= DepthTextureMode.Depth;
        }

        private void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            if (MotionBlurMat != null)
            {
                MotionBlurMat.SetFloat("_BlurSize", BlurSize);
                MotionBlurMat.SetMatrix("_PreViewProjMatrix", mPreViewProjMatrix); //设置前一帧的 视角投影矩阵
                Matrix4x4 curViewProjMatrix = Camera.projectionMatrix * Camera.worldToCameraMatrix; //当前帧的 视角投影矩阵
                Matrix4x4 curViewProjInverseMatrix = curViewProjMatrix.inverse; //逆矩阵
                MotionBlurMat.SetMatrix("_CurViewProjInverseMatrix", curViewProjInverseMatrix); //设置当前帧的 视角投影矩阵
                mPreViewProjMatrix = curViewProjMatrix;
                Graphics.Blit(source, destination, MotionBlurMat);
            }
            else
            {
                Graphics.Blit(source, destination);
            }
        }
    }
}